package datenverwaltung;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.swing.JProgressBar;

import com.main.meldungsverwaltung.LabelTextField;

/**
 * L�dt Informationen zu einem bestimmten Tracker herunter.
 * 
 * @author Felix
 * 
 */
public class TrackerInfoDownload extends Thread implements DBVerbindung {

	private Tracker tracker;
	private String id;
	private JProgressBar progressBar;
	private LabelTextField idText, zuverl;
	private static Connection connection;

	public TrackerInfoDownload(String id, JProgressBar progressBar,
			LabelTextField idText, LabelTextField zuverl) {
		super();
		this.id = id;
		this.progressBar = progressBar;
		this.idText = idText;
		this.zuverl = zuverl;
		if (connection == null)
			try {
				connection = getConnection();
			} catch (Exception e) {
				e.printStackTrace();
			}
	}

	@Override
	public void run() {
		try {
			tracker = getTrackerInfo(id);
			idText.setTextFieldText(tracker.getId());
			zuverl.setTextFieldText(Float.toString(tracker
					.getZuverlaessigkeit()));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			progressBar.setIndeterminate(false);
		}
	}

	@Override
	public void interrupt() {
	}

	@Override
	public Connection getConnection() throws Exception {
		Connection connection;
		Class.forName("com.mysql.jdbc.Driver");
		connection = DriverManager.getConnection(DB_CONNECTION_URL,
				DB_USERNAME, DB_PASSWORD);
		return connection;
	}

	@Override
	public ResultSet executeStatementOnDB(String select) throws Exception {
		Statement statement = connection.createStatement();
		ResultSet result = statement.executeQuery(select);
		return result;
	}

	/**
	 * Selektiert die Informationen zum Tracker mit der übergebenen ID.
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	public Tracker getTrackerInfo(String id) throws Exception {
		String select = "select tracker.id,zuverlaessigkeit,sum(anzAktiv),sum(anzInaktiv),sum(anzAktiv)+sum(anzInaktiv) anzahlGesamt from tracker,meldung where tracker.id="
				+ id
				+ " and tracker.id=meldung.tracker_id group by tracker.id,tracker.zuverlaessigkeit;";
		ResultSet result = executeStatementOnDB(select);
		result.next();
		System.out.println(id);
		Tracker t = new Tracker(result.getString("id"), Float.parseFloat(result
				.getString("zuverlaessigkeit")), 0, Integer.parseInt(result
				.getString("sum(anzAktiv)")), Integer.parseInt(result
				.getString("sum(anzInaktiv)")), Integer.parseInt(result
				.getString("anzahlGesamt")));

		return t;
	}

	public Tracker getTracker() {
		return tracker;
	}

}
